package com.mdinfo.gw.door.driver.aopu;

import com.mdinfo.gw.door.driver.utils.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Administrator on 2018/1/31.
 */

public class AopuReadOpration {

    private Integer accessId;
    private Logger logger = LoggerFactory.getLogger(AopuReadOpration.class);

    public AopuReadOpration(Integer accessId){
        this.accessId = accessId;
    }

    public void execute(ChannelHandlerContext ctx,byte[] req){
        Byte event = req[2];
        /**心跳回复*/
        if(event.intValue()==0x56){
            heartbeatAnswer(ctx);
        }
        /**刷卡*/
        else if(event.intValue()==0x53){
            brushCardAnswer(ctx,req);
        }
        /**远程开门响应*/
        else if(event.intValue()==0x2c){
            remoteOpen(req);
        }
        /**远程关门响应*/
        else if(event.intValue()==0x2e){
            remoteClose(req);
        }
//        System.out.println(ByteUtil.bytes2Hex2(req));
    }

    /**心跳回复*/
    private void heartbeatAnswer(ChannelHandlerContext ctx){

//        logger.info("心跳回复");
        ByteBuf byteBuf = Unpooled.copiedBuffer(ByteUtil.heartbeatAnswer());
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 刷卡事件
     */
    private void brushCardAnswer(ChannelHandlerContext ctx,byte[] req){

        // 门id
        int doorId = ((Byte)req[4]).intValue();
        // 流水id
        int brushId = ((Byte)req[20]).intValue();
        //事件类型
        int eventType = ((Byte)req[17]).intValue();
        String eventTypeStr = "";
        if(eventType==10){
            eventTypeStr = "出门";
        }else if(eventType==11){
            eventTypeStr = "进门";
        }else if(eventType==14){
            eventTypeStr = "密码开门";
        }else if(eventType==16){
            eventTypeStr = "无效卡进入";
        }else if(eventType==17){
            eventTypeStr = "无效卡出";
        }else if(eventType==59){
            eventTypeStr = "出门按钮打开";
        }else if(eventType==100){
            eventTypeStr = "门开";
        }else if(eventType==101){
            eventTypeStr = "门关";
        }else if(eventType==1){
            eventTypeStr = "无效卡号";
        }
        String cardId = ByteUtil.getCardId(req[10],req[9],req[8],req[7]);

        System.out.println("门禁id:"+accessId+" 门序号:"+doorId+" 门卡:" + cardId+" 事件:"+eventTypeStr+" 流水id:"+brushId);
        
        ByteBuf byteBuf = Unpooled.copiedBuffer(ByteUtil.brushCardAnswer(doorId,brushId));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 远程开门响应
     */
    private void remoteOpen(byte[] req){
        if(req[7]==0x06){
            logger.info("远程开门成功");
        }
    }

    /**
     * 远程关门响应
     */
    private void remoteClose(byte[] req){
        if(req[7]==0x06){
            logger.info("远程关门成功");
        }
    }
}
